﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace JobDemo01.Job
{
    class ImagingContext(JobContext ctx, List<int> indices = null)
    {
        readonly Channel<ImagingResult> channel = Channel.CreateUnbounded<ImagingResult>();

        public IIndexer Indexer => indices == null ? new Indexer() : new ListIndexer(indices);

        public JobContext JobContext => ctx;

        public IAsyncEnumerable<ImagingResult> Source => channel.Reader.ReadAllAsync();

        public Task CheckPoint()
        {
            return ctx.CheckPoint();
        }

        public void Write(ImagingResult img)
        {
            channel.Writer.TryWrite(img);
        }

        public Task<AlignmentHint> AwaitManualAssist()
        {
            return ctx.AwaitManualAssist();
        }

        public void Complete(bool requireConfirmation)
        {
            channel.Writer.TryComplete();
            if (requireConfirmation)
            {
                ctx.OnProcessingFinished();
            }
            else
            {
                ctx.Complete();
            }
        }

        public void Complete(Exception ex)
        {
            channel.Writer.TryComplete(ex);
            ctx.Complete(ex);
        }
    }
}
